package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserLoginService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 微信登录
     * @return
     * @param userLoginDTO
     */
    public User wxLogin(UserLoginDTO userLoginDTO){
        String openid = getOpenid(userLoginDTO);

        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        User user = userMapper.getByOpenid(openid);
        if (user == null){
             user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();

             userMapper.insert(user);
        }
        return user;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param userLoginDTO
     * @return
     */
    private String getOpenid(UserLoginDTO userLoginDTO)  {
        Map<String,String> paramMap = new HashMap<>();

        //用户的登陆凭证
        paramMap.put("js_code", userLoginDTO.getCode());
        //小程序的appid
        paramMap.put("appid",weChatProperties.getAppid());
        //小程序的密钥
        paramMap.put("secret",weChatProperties.getSecret());
        //微信授权类型
        paramMap.put("grant_type","authorization_code");

        //调用微信接口服务，获得当前用户的唯一的openid
        String json = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        //解析json类数据
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
